package org.example.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.shardingsphere.driver.api.ShardingSphereDataSourceFactory;
import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;
import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;
import org.example.datasource.DynamicDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
public class DynamicDatasourceConfig {

    // 定义物理 master 数据源
    @Bean("physicalMaster")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource physicalMaster() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
//    @Primary
    public DataSource primaryDataSource(@Qualifier("physicalMaster") DataSource physicalMaster) {
        return physicalMaster;
    }

    @Bean
    @Primary
    public DynamicDataSource dynamicDataSource(
            @Qualifier("slaveDataSource") DataSource slaveDataSource,
//            @Qualifier("shardingMaster") DataSource shardingMaster,
            @Qualifier("physicalMaster") DataSource physicalMaster) {

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 添加所有数据源
        dynamicDataSource.addDataSource("slaveDataSource", slaveDataSource);
//        dynamicDataSource.addDataSource("shardingMaster", shardingMaster);
        dynamicDataSource.addDataSource("physicalMaster", physicalMaster);
        // 设置默认数据源
        dynamicDataSource.setDefaultTargetDataSource(physicalMaster);
        return dynamicDataSource;
    }

    // 其他未分表数据源（如 slave）
    @Bean("slaveDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    //pg 数据源
    @Bean("pgDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.pg")
    public DataSource pgDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

}